{extend name="common@base" /}
{block name="content"}
<link rel="stylesheet" href="__CSS__/cropper.min.css">
<style>
  .hand {
    cursor: pointer;
  }
</style>

<style>
  /**/
  .thumb {
    margin-top: 25px;
    display: flex;
    flex-direction: row;
  }
  .thumb > * {
    align-self: flex-start;
  }
  .thumb img {
    margin-right: 10px;
  }
  /**/
  #app ul {
    list-style: none;
    display: flex;
  }
  #app ul li img {
    max-height: 100px;
    width: auto;
  }
  #app > div > div > img {
    max-height: 100px;
    width: auto;
  }

  /*crop*/
  #app,
  .thumb {
    border: solid 1px #eee;
    padding: 20px;
  }

  #app .image {
    margin: 0 auto;
    position: relative;
  }

  #app #pc .image {
    width: 300px;
    height: 400px;
  }

  #app #mobile .image {
    /*width: 240px;*/
    width: 300px;
    /*height: 200px;*/
    height: 250px;
  }

  #app .image img.origin {
    max-width: 100%;
    max-height: 100%;
  }

  /* mask prompt */
  .mask.prompt {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 30px;
    line-height: 30px;
    background-color: rgba(0, 0, 0, 0.5);
    text-align: center;
    overflow: hidden;
  }

  .mask.prompt.horizontal:after {
    display: block;
    background-image: url("http://qiniu.xingtan.xyz/horizontal.png");
    background-size: auto 16px;
    background-repeat: no-repeat;
    background-position: left;
    content: '左右调整图片，选择合适区域生成缩略图';
    font-size: 14px;
    color: #fff;
    padding-left: 40px;
  }

  .mask.prompt.vertical:after {
    display: block;
    background-image: url("http://qiniu.xingtan.xyz/vertical.png");
    background-size: auto 26px;
    background-repeat: no-repeat;
    background-position: 0 2px;
    content: '上下调整图片，选择合适区域生成缩略图';
    font-size: 14px;
    color: #fff;
    padding-left: 25px;
  }

  .mask.prompt.exact:after {
    background-image: url("http://qiniu.xingtan.xyz/exact.png");
    background-size: auto 16px;
    background-repeat: no-repeat;
    background-position: left;
    content: '完美的缩略图';
    font-size: 14px;
    color: #fff;
    padding-left: 30px;
  }
</style>

<section class="content">
  <div class="row">
    <div class="col-xs-12" id="vueContainer">
      <form action="" method="post" class="form">
        <div class="box box-primary">
          <div class="box-body">
            <div class="form-group">
              <label for="">分类
              {:form_dropdown('form[cate_id]',$cates,$row.cate_id,'class="form-control"')}
              </label>
            </div>
            <div class="form-group">
              <label for="">标题</label>
              <input type="text" name="form[title]" value="{$row.title}" class="form-control">
            </div>
            <div class="form-group hide">
              <label for="">简介（最多100字）</label>
              <textarea name="form[desc]" cols="30" rows="3" class="form-control">{$row.desc}</textarea>
              <p></p>
            </div>
            <div class="form-group">
              <label for="">内容</label>
              <script id="container" name="form[content]" type="text/plain">{$row.content}</script>
            </div>

            <div class="form-group">
              <label>封面图</label>


              <div class="thumb">
                <!--<img class="pc"  src="{$row&&$row.thumb  ? $row.thumb : ''}" alt="">-->
                <!--<img class="mobile" src="{$row&&$row.mobile_thumb  ? $row.mobile_thumb : ''}" alt="">-->
                <img class="pc"  :src="previewThumbs.pc" alt="">
                <img class="mobile" :src="previewThumbs.mobile" alt="">

                <button v-show="images.length" class="btn btn-sm btn-success" @click.prevent="modal.modal('show')">设置缩略图</button>
                <!---->
              </div>

              <div class="hide">
                <!--<input class="pc" type="text" name="form[thumb]" value="{$row.thumb}">-->
                <!--<input class="mobile" type="text" name="form[mobile_thumb]" value="{$row.mobile_thumb}">-->
                <input class="pc" type="text" name="form[thumb]" v-model="inputThumbs.pc">
                <input class="mobile" type="text" name="form[mobile_thumb]" v-model="inputThumbs.mobile">
              </div>
            </div>

            <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
              <div class="modal-dialog" role="document" style="width: 1000px;">
                <div class="modal-content">
                  <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">设置封面图</h4>
                  </div>
                  <div class="modal-body">
                    <div class="img-container">
                      <!--<img id="image" src="https://avatars0.githubusercontent.com/u/3456749">-->
                      <div id="app">
                        <div class="container-fluid" v-show="images.length">

                          <div class="row" style="display: flex;align-items: center;">
                            <div class="col-md-6" id="pc">
                              <div class="image">
                                <img alt="" class="origin">
                                <div class="mask prompt"></div>
                              </div>
                            </div>
                            <div class="col-md-6" id="mobile">
                              <div class="image">
                                <img alt="" class="origin">
                                <div class="mask prompt"></div>
                              </div>
                            </div>
                          </div>

                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-default" @click.prevent="next">切换</button>
                    <button type="button" class="btn btn-primary" @click.prevent="crop">确认裁剪</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                  </div>
                </div>
              </div>
            </div>

          </div>
          <div class="box-footer">
            <div>
              <!--<button class="btn btn-primary js-ajax-submit" type="submit">保存</button>-->
              <button class="btn btn-primary" type="submit" ref="submitButton" @click="formSubmit($event)">保存</button>
              <!--<button class="btn btn-primary" type="submit" data-message="are you ok?" ref="submitButton">保存</button>-->
              <a href="javascript:history.back()" class="btn btn-default">返回</a>
            </div>
          </div>
        </div>

      </form>
    </div>
  </div>
</section>
{/block}
{block name="page_script"}

<script>
  require(["ueditor", "vue", "cropperjs", "layer_config", "ajaxForm"], function (UEditor, Vue, Cropper, layer, ajaxForm) {

    const EditID = {$row.id > 0 ? $row.id : 0};
    const Thumbs = {
      'pc': '{$row.thumb | default=''}',
      'mobile': '{$row.mobile_thumb | default=''}'
    };

    // crop configuration
    const configs = [
      {
        id: 'pc',
        width: 150,
        height: 200
      },
      {
        id: 'mobile',
        width: 120,
        height: 100
      }
    ]

    const app = new Vue({
      // el: '#app',
      el: '#vueContainer',
      data: () => ({
        //
        modal: null,
        //
        previewThumbs: {
          pc: Thumbs.pc,
          mobile: Thumbs.mobile
        },
        //
        inputThumbs: {
          pc: Thumbs.pc,
          mobile: Thumbs.mobile
        },
        // ueditor instance
        ue: null,
        // images inside of the ueditor content
        images: [],
        // current image to being cropped
        index: 0,
        // pc and mobile cropper instance
        croppers: {}
      }),
      computed: {
        src: function () {
          return this.images[this.index]
        }
      },
      watch: {
        src: function (newValue, oldValue) {
          // console.log(newValue, oldValue)
          this.createCropContainer()
        },
        images: function (newValue, oldValue) {
          // console.log(newValue, oldValue)
          if (oldValue.length === 0) {
            // console.log('initialize')
            this.index = 0
          } else if (newValue.length === 0) {
            // console.log('no images any more')
            this.index = 0
          } else {
            let previousImage = oldValue[this.index]
            if (newValue.some((img, index) => {
              let exist = img === previousImage
              if (exist) {
                this.index = index
              }
              return exist
            })) {
              // console.log('the image being cropped is still in the images')
            } else {
              // console.log('the image being cropped is gone')
              this.index = 0
            }

          }
        },
        index: function (newValue, oldValue) {
          console.log(newValue, oldValue)
        }
      },
      mounted: function () {
        this.initUEditor()
        this.initModal()
      },
      methods: {
        initModal: function () {
          this.modal = $('#modal')
          this.modal.on('shown.bs.modal', () => {
            // console.log('modal shown')
            this.createCropContainer()
          }).on('hidden.bs.modal', () => {
            // console.log('modal hidden')
            this.destroyCropInstances()
          });
          // this.modal.modal('show')
        },
        initUEditor: function () {
          this.ue = UEditor.getEditor('container', {
            UEDITOR_HOME_URL: "__STATIC__/ueditor/",
            autoHeight: false,
            initialFrameHeight: 520,
            autoHeightEnabled: false,
            scaleEnabled: true
          });
          this.ue.ready(() => {
            this.ue.addListener('contentchange', this.contentChange);

            // init the images when ue is ready
            // this.contentChange()
            this.ue.trigger('contentchange')

          })
        },
        destroyCropInstances: function () {
          Object.keys(this.croppers).forEach(k => {
            if (this.croppers[k]) this.croppers[k].destroy()
            this.croppers[k] = null
          })
          this.croppers = {}
        },
        createCropContainer: function () {
          this.destroyCropInstances()

          configs.forEach(config => {
            let container = document.getElementById(config.id)
            let image = container.querySelector('img.origin')
            let maskPrompt = container.querySelector('.mask.prompt')

            // vue.js binding src not work when destroy and recreate cropper.js instance
            image.src = this.src

            //
            let cropper = new Cropper(image, {
              aspectRatio: config.width / config.height,
              viewMode: 3,
              dragMode: 'move',
              center: false,
              // guides: false,
              highlight: false,
              cropBoxMovable: false,
              cropBoxResizable: false,
              toggleDragModeOnDblclick: false,
              rotatable: false,
              scalable: false,
              zoomable: false,
              zoomOnTouch: false,
              zoomOnWheel: false,
              ready: function () {
                let cropper = this.cropper
                let containerData = cropper.getContainerData();
                cropper.setCropBoxData({
                  width: containerData.width,
                  height: containerData.height
                })
                // mask prompt
                let imageData = cropper.getImageData()
                // 150/200
                const ratio = 100 * config.width / config.height
                maskPrompt.classList.remove('exact')
                maskPrompt.classList.remove('horizontal')
                maskPrompt.classList.remove('vertical')
                if (imageData.aspectRatio * 100 === ratio) {
                  maskPrompt.classList.add('exact')
                } else if (imageData.aspectRatio * 100 > ratio) {
                  maskPrompt.classList.add('horizontal')
                } else if (imageData.aspectRatio * 100 < ratio) {
                  maskPrompt.classList.add('vertical')
                }
              }
            })
            //
            this.croppers[config.id] = cropper
          })
        },
        contentChange: function (editor) {
          let html = this.ue.getContent()
          let root = UEditor.htmlparser(html, true)
          let imgs = root.getNodesByTagName('img')

          let srcs = []

          if( imgs.some(img => {
            let src = img.getAttr('src')
            let uploading = /spacer.gif$/i.test(src)
            if (! uploading) {
              srcs.push(src)
            }
            return uploading
          }) ) {

            setTimeout(this.contentChange, 1000)

          } else {

            if (srcs.length === this.images.length && srcs.every((src, index) => {
              return src === this.images[index]
            })) {
              // console.log('images not changed')
            } else {
              this.images = srcs
            }
            // 直接赋值会触发watch，即使没有修改图片
            // this.images = srcs
          }
        },
        next: function () {
          let index = this.index + 1
          if (index === this.images.length) {
            index = 0
          }
          this.index = index
        },
        crop: function () {

          configs.forEach(config => {
            let canvas
            let cropper = this.croppers[config.id]
            if (cropper) {
              canvas = cropper.getCroppedCanvas({
                width: config.width,
                height: config.height
              })

              let base64URL = canvas.toDataURL()

              this.previewThumbs[config.id] = base64URL

              let imageType = base64URL.split(';')[0].split('/')[1]

              canvas.toBlob(blob => {

                let formData = new FormData()

                  formData.append('image', blob, `${config.id}.${imageType}`)
                  // formData.append('platform', config.id);

                  $.ajax('/admin/knowledge/saveCrop', {
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,

                    success: data => {
                      console.log('ajax success')
                      console.log(data)
                      if (data.msg === 'ok') {
                        // $(`div.thumb>img.${data.platform}`).attr('src', data.src)
                        // $(`input.${data.platform}`).val(data.src)
                        this.previewThumbs[config.id] = data.src
                        this.inputThumbs[config.id] = data.src
                      } else {
                        this.previewThumbs[config.id] = Thumbs[config.id]
                      }
                    },

                    error: () => {
                      this.previewThumbs[config.id] = Thumbs[config.id]
                      console.log('ajax error')
                    },

                    complete: () => {
                      console.log('ajax complete')
                      this.modal.modal('hide')
                      // if (EditID === 0) {
                      //   this.$refs['submitButton'].click()
                      // }
                    }
                  })
              })

            }
          })
        },
        ifNoThumbs: function () {
          if (this.images.length > 0 && (this.inputThumbs.pc == '' || this.inputThumbs.mobile == '')) {
            this.modal.modal('show')
            // console.log('内容中有图片呢，请设置缩略图吧')
            return true
          }
          return false
        },
        // copy from footer-js.html
        formSubmit: function (event) {
          if ( this.ifNoThumbs() ) {
            event.preventDefault()
            return false
          }
          // console.log('check thumb passed')
          // return

          let btn = $(this.$refs.submitButton)
          // var btn = $(this)
                  , form = btn.parents('form')
                  , message = btn.data('message')
                  , options = {offset: "150px"}
                  , href = form.attr("action")
          ;
          var ajaxFormOption = {
            type: "post",  //提交方式
            dataType: "json", //数据类型
            //data: myData,//自定义数据参数，视情况添加
            success: function (result) { //提交成功的回调函数
              if (result.code == 0) {
                js_alert(result.msg);
                return false;
              }
              layer.msg(result.msg, {
                time: 1000,
                offset: '150px',
                icon: 1,
                area: '30%',
                anim: 2,
                fixed: false,
              }, function (index) {
                if (result.url) {
                  window.location.href = result.url;
                }
                layer.close(index);
                btn.attr("disabled", false);
              });

            }, error: function (result) {
              btn.attr("disabled", false);
              layer.alert('网络错误');
            }
          };
          console.log(ajaxFormOption);

          if (message) {
            var args = form.serialize();
            layer.confirm(message, options, function (index) {
              $.ajax({
                "url": href,
                "type": "post",
                "data": args,
                "success": function (result) {
                  if (result.code == 1) {
                    js_message(result.msg, true);
                  } else {
                    js_message(result);
                  }
                },
                "error": function (result) {
                  js_alert("{:lang('network error')}");
                }
              })
            });
            return false;
          } else {
            form.ajaxForm(ajaxFormOption);
          }
        }
        // end of formSubmit method
      }
      // end of methods
    })
  })
</script>

{/block}





